package com.cac.demo.service.system;

import com.cac.demo.dao.system.MenuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class SystemQueryService {
    @Autowired
    private MenuDao menuDao;

    public List<HashMap> queryMenu(HashMap map){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String account = (String) request.getSession().getAttribute("account");
        if(Objects.isNull(account)){
            account="-1";
        }
        map.put("account",account);
        return menuDao.queryMenu(map);
    }

    public List<HashMap> queryRole(HashMap role){
        return menuDao.queryRole(role);
    }

    public List<String> queryRoleMenus(String tsRoleId){
        return menuDao.queryRoleMenus(tsRoleId);
    }
    //查询菜单树，将查询出来的数据封装为树形结构
    public List<HashMap> queryMenuTree(){
        HashMap map = new HashMap();
        map.put("grade",1);
        List<HashMap> parents = menuDao.queryMenuTree();
        if(parents==null||parents.size()==0){
            return null;
        }
        List<HashMap> menuTreeList = new ArrayList<>();
        int curIndex = -1;
        for(HashMap par : parents){
            if("0".equals(par.get("grade").toString())){//根节点不做处理
                continue;
            }
            if("1".equals(par.get("grade").toString())){
                menuTreeList.add(par);
                curIndex++;
            }else if("2".equals(par.get("grade").toString())){
                HashMap tmp = menuTreeList.get(curIndex);
                if(tmp.containsKey("children")){ //子节点添加兄弟元素
                    List<HashMap> childList = (List<HashMap>) tmp.get("children");
                    childList.add(par);
                }else{  //父节点添加子节点
                    List<HashMap> tmpList = new ArrayList<>();
                    tmpList.add(par);
                    tmp.put("children",tmpList);
                }
            }
        }
        return menuTreeList;
    }
    //查询用户
    public List<HashMap> searchUser(String text){
        return menuDao.searchUser(text);
    }

    //查询用户详细信息
    public List<HashMap> queryUserDetail(HashMap user){
        return menuDao.queryUserDetail(user);
    }
}
